package cn.wolfcode.mq.listener;

import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMQResult;
import cn.wolfcode.mq.OrderMessage;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

@Component
@RocketMQMessageListener(
        consumerGroup = "OderPeddingGroup",
        topic = MQConstant.ORDER_PEDDING_TOPIC
)
//ORDER_PEDDING_TOPIC
public class OderPeddingListener implements RocketMQListener<OrderMessage> {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private IOrderInfoService orderInfoService;

    @Override
    public void onMessage(OrderMessage orderMessage) {
        //处理
        System.err.println("第二条流开始...");
        //创建一个结果对象
        OrderMQResult orderMQResult = new OrderMQResult();
        orderMQResult.setTime(orderMessage.getTime());
        orderMQResult.setSeckillId(orderMessage.getSeckillId());
        orderMQResult.setToken(orderMessage.getToken());


        //消费逻辑
        //1 调用Service层进行表操作
        String tag = MQConstant.ORDER_RESULT_SUCCESS_TAG;
        try {
            String orderNo = orderInfoService.order(orderMessage);
            orderMQResult.setOrderNo(orderNo);
            Message<OrderMQResult> message = MessageBuilder.withPayload(orderMQResult).build();
            //2 如果表操作成功,发延时消息
            rocketMQTemplate.syncSend(MQConstant.ORDER_PAY_TIMEOUT_TOPIC, message, 5000l,
                    MQConstant.ORDER_PAY_TIMEOUT_DELAY_LEVEL);
        } catch (Exception e) {
            //3 表操作失败,发送失败标签的消息
            e.printStackTrace();
            orderMQResult.setMsg(SeckillCodeMsg.SECKILL_ERROR.getMsg());  //表操作失败才有
            orderMQResult.setCode(SeckillCodeMsg.SECKILL_ERROR.getCode());  //表操作失败才有
            tag = MQConstant.ORDER_RESULT_FAIL_TAG;
        } finally {
            //4无论成功还是失败,发结果消息给消息服务
            rocketMQTemplate.sendOneWay(MQConstant.ORDER_RESULT_TOPIC + ":" +
                    tag, orderMQResult);
        }
    }
}
